<?php
/**
 * @File:    Utils.php
 * @Author:  LiaoJiangYi
 * @Website: www.jyliao.com
 * @Wechat:  jyliao_vip
 * @QQ:      527532113
 * @Date:    2016/1/11 17:16
 */
namespace Ext;
final class Utils
{
    public static function formatTime($time)
    {
        $t = time() - $time;
        if ($t < 1) return '刚刚';
        $f = array(
            '31536000' => '年',
            '2592000' => '个月',
            '604800' => '星期',
            '86400' => '天',
            '3600' => '小时',
            '60' => '分钟',
            '1' => '秒'
        );
        foreach ($f as $k => $v) {
            if (0 != $c = floor($t / (int)$k)) {
                return $c . $v . '前';
            }
        }
    }

    public static function mkdir($dir, $mod = 0755)
    {
        if (is_dir($dir)) return true;
        return mkdir($dir, $mod, true);
    }

    public static function saveBase64Image($savePath, $data, $fileName = null)
    {
        if (substr($savePath, -1) != '/') {
            return false;
        }
        if (substr($data, 0, 11) != 'data:image/') {
            return false;
        }
        if (!$fileName) $fileName = md5($data);
        preg_match("/image\/(.+)\;/", $data, $ext);
        $ext = $ext[1];
        $data = preg_replace("/data:image\/(.+)\;base64\,/", "", $data);
        $data = base64_decode($data);
        $config = \Phalcon\Di::getDefault()->get('config')->application;
        $path = $config->upfilePath . $savePath . $fileName . '.' . $ext;
        $savePath = $config->upfileDir . $savePath;
        self::mkdir($savePath);
        $savePath .= $fileName . '.' . $ext;
        if (file_exists($savePath)) return $path;
        $ret = file_put_contents($savePath, $data);
        if (!$ret) return false;
        return $path;
    }

    public static function getIp()
    {
        $ip = null;
        if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if ($ip) {
                array_unshift($ips, $ip);
                $ip = FALSE;
            }
            for ($i = 0; $i < count($ips); $i++) {
                if (!eregi("^(10|172\.16|192\.168)\.", $ips[$i])) {
                    $ip = $ips[$i];
                    break;
                }
            }
        }
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }

    public static function unicodeDecode($name)
    {
        // 转换编码，将Unicode编码转换成可以浏览的utf-8编码
        $pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
        preg_match_all($pattern, $name, $matches);
        if (!empty($matches)) {
            $name = '';
            for ($j = 0; $j < count($matches[0]); $j++) {
                $str = $matches[0][$j];
                if (strpos($str, '\\u') === 0) {
                    $code = base_convert(substr($str, 2, 2), 16, 10);
                    $code2 = base_convert(substr($str, 4), 16, 10);
                    $c = chr($code) . chr($code2);
                    $c = iconv('UCS-2', 'UTF-8', $c);
                    $name .= $c;
                } else {
                    $name .= $str;
                }
            }
        }
        return $name;
    }

    function ImageCreateFromBMP($filename)
    {
        if (!$f1 = fopen($filename, "rb")) return FALSE;

        $FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1, 14));
        if ($FILE ['file_type'] != 19778) return FALSE;

        $BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel' . '/Vcompression/Vsize_bitmap/Vhoriz_resolution' .
            '/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1, 40));
        $BMP ['colors'] = pow(2, $BMP ['bits_per_pixel']);
        if ($BMP ['size_bitmap'] == 0) $BMP ['size_bitmap'] = $FILE ['file_size'] - $FILE ['bitmap_offset'];
        $BMP ['bytes_per_pixel'] = $BMP ['bits_per_pixel'] / 8;
        $BMP ['bytes_per_pixel2'] = ceil($BMP ['bytes_per_pixel']);
        $BMP ['decal'] = ($BMP ['width'] * $BMP ['bytes_per_pixel'] / 4);
        $BMP ['decal'] -= floor($BMP ['width'] * $BMP ['bytes_per_pixel'] / 4);
        $BMP ['decal'] = 4 - (4 * $BMP ['decal']);
        if ($BMP ['decal'] == 4) $BMP ['decal'] = 0;

        $PALETTE = array();
        if ($BMP ['colors'] < 16777216) {
            $PALETTE = unpack('V' . $BMP ['colors'], fread($f1, $BMP ['colors'] * 4));
        }

        $IMG = fread($f1, $BMP ['size_bitmap']);
        $VIDE = chr(0);
        $res = imagecreatetruecolor($BMP ['width'], $BMP ['height']);
        $P = 0;
        $Y = $BMP ['height'] - 1;
        while ($Y >= 0) {
            $X = 0;
            while ($X < $BMP ['width']) {
                if ($BMP ['bits_per_pixel'] == 24)
                    $COLOR = unpack("V", substr($IMG, $P, 3) . $VIDE);
                elseif ($BMP ['bits_per_pixel'] == 16) {
                    $COLOR = unpack("n", substr($IMG, $P, 2));
                    $COLOR [1] = $PALETTE [$COLOR [1] + 1];
                } elseif ($BMP ['bits_per_pixel'] == 8) {
                    $COLOR = unpack("n", $VIDE . substr($IMG, $P, 1));
                    $COLOR [1] = $PALETTE [$COLOR [1] + 1];
                } elseif ($BMP ['bits_per_pixel'] == 4) {
                    $COLOR = unpack("n", $VIDE . substr($IMG, floor($P), 1));
                    if (($P * 2) % 2 == 0) $COLOR [1] = ($COLOR [1] >> 4); else $COLOR [1] = ($COLOR [1] & 0x0F);
                    $COLOR [1] = $PALETTE [$COLOR [1] + 1];
                } elseif ($BMP ['bits_per_pixel'] == 1) {
                    $COLOR = unpack("n", $VIDE . substr($IMG, floor($P), 1));
                    if (($P * 8) % 8 == 0) $COLOR [1] = $COLOR [1] >> 7;
                    elseif (($P * 8) % 8 == 1) $COLOR [1] = ($COLOR [1] & 0x40) >> 6;
                    elseif (($P * 8) % 8 == 2) $COLOR [1] = ($COLOR [1] & 0x20) >> 5;
                    elseif (($P * 8) % 8 == 3) $COLOR [1] = ($COLOR [1] & 0x10) >> 4;
                    elseif (($P * 8) % 8 == 4) $COLOR [1] = ($COLOR [1] & 0x8) >> 3;
                    elseif (($P * 8) % 8 == 5) $COLOR [1] = ($COLOR [1] & 0x4) >> 2;
                    elseif (($P * 8) % 8 == 6) $COLOR [1] = ($COLOR [1] & 0x2) >> 1;
                    elseif (($P * 8) % 8 == 7) $COLOR [1] = ($COLOR [1] & 0x1);
                    $COLOR [1] = $PALETTE [$COLOR [1] + 1];
                } else
                    return FALSE;
                imagesetpixel($res, $X, $Y, $COLOR [1]);
                $X++;
                $P += $BMP ['bytes_per_pixel'];
            }
            $Y--;
            $P += $BMP ['decal'];
        }
        fclose($f1);
        return $res;
    }

    function ImageToJPG($srcFile, $dstFile, $quality = 80, $toWidth = 0, $toHeight = 0)
    {
        $data = @getimagesize($srcFile);
        switch ($data['2']) {
            case 1:
                $im = imagecreatefromgif($srcFile);
                break;
            case 2:
                $im = imagecreatefromjpeg($srcFile);
                break;
            case 3:
                $im = imagecreatefrompng($srcFile);
                break;
            case 6:
                $im = self::ImageCreateFromBMP($srcFile);
                break;
        }
        $srcW = @imagesx($im);
        $srcH = @imagesy($im);
        if ($toWidth && $toHeight) {
            $dstX = $toWidth;
            $dstY = $toHeight;
        } else {
            $dstX = $srcW;
            $dstY = $srcH;
        }
        $ni = @imagecreatetruecolor($dstX, $dstY);
        @imagecopyresampled($ni, $im, 0, 0, 0, 0, $dstX, $dstY, $srcW, $srcH);
        @imagejpeg($ni, $dstFile, $quality);
        @imagedestroy($im);
        @imagedestroy($ni);
    }

    public static function textAreaOutput($value)
    {
        $value = str_replace("\n", "<br>", $value);
        return $value;
    }

    public static function outPut($string)
    {
        if(!$string)return $string;
        return htmlspecialchars_decode($string);
    }

    public static function removeEmoji($clean_text)
    {
        // Match Emoticons
        $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
        $clean_text = preg_replace($regexEmoticons, '', $clean_text);
        // Match Miscellaneous Symbols and Pictographs
        $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
        $clean_text = preg_replace($regexSymbols, '', $clean_text);
        // Match Transport And Map Symbols
        $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
        $clean_text = preg_replace($regexTransport, '', $clean_text);
        // Match Miscellaneous Symbols
        $regexMisc = '/[\x{2600}-\x{26FF}]/u';
        $clean_text = preg_replace($regexMisc, '', $clean_text);
        // Match Dingbats
        $regexDingbats = '/[\x{2700}-\x{27BF}]/u';
        $clean_text = preg_replace($regexDingbats, '', $clean_text);
        return $clean_text;
    }

    public static function createGUid($namespace = '')
    {
        $guid = '';
        $uid = uniqid("", true);
        $data = $namespace;
        $data .= $_SERVER['REQUEST_TIME'];
        $data .= $_SERVER['HTTP_USER_AGENT'];
        $data .= $_SERVER['REMOTE_ADDR'];
        $data .= $_SERVER['REMOTE_PORT'];
        $hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
        $guid = implode('-', str_split($hash, 4));
        return $guid;
    }
    public static function get16Md5($string)
    {
        return substr(md5(md5($string)),8,16);
    }
    public static function is_json($string)
    {
        json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);
    }
    public static function securityHash($string)
    {
        $security = new \Phalcon\Security();
        $security->setDefaultHash('+Nodm23e9^%&*+');
        $security->setWorkFactor(12);
        return $security->hash($string);
    }
}